package org.mixare;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import com.google.android.maps.GeoPoint;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PoiLocation extends Activity implements LocationListener  {//java file that allows for new poi to be added 
	
	private static final int CAMERA_REQUEST = 1888;//needs geo location and save method
	private ImageView imageView;
	double Lat=0.0,Long=0.0;
	boolean mExternalStorageAvailable = false;
	boolean mExternalStorageWriteable = false;
	String state = Environment.getExternalStorageState();
	boolean success = false;

	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.newpoi);
        this.imageView = (ImageView)this.findViewById(R.id.Poiphoto);
        
		Button save = (Button) findViewById(R.id.savepoi);
		
		LocationManager locManager;
		locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
        Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(location != null)                                
        {
            Lat = location.getLatitude();
            Long = location.getLongitude();
        }  
	    save.setOnClickListener(new View.OnClickListener(){
		public void onClick(View v){
			EditText titleText = (EditText)findViewById(R.id.newPoiTitle);
			EditText descText = (EditText)findViewById(R.id.newpoidescription);
			
			String Title= titleText.getText().toString();
			String Description= descText.getText().toString();
			 
			 /*LocationManager locationMng = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		     LocationListener locationLstnr = new PoiLocation();
		     locationMng.requestLocationUpdates( LocationManager.GPS_PROVIDER, 100, 10, locationLstnr);
		     Location location = locationMng.getLastKnownLocation(LocationManager.GPS_PROVIDER);*/
			

		  
		     //Long = location.getLongitude();
		     //Lat = location.getLatitude();
		      
		      if (Environment.MEDIA_MOUNTED.equals(state)) {
		    	  File path = Environment.getExternalStorageDirectory();
		    	  File folder = new File(path,"eaglevision");
		    	  File file= new File(folder,Title);
		    	  File pic= new File(file,Title+".png");
		    	  
		    	  try{
		    		
		    		  file.mkdirs();
		    		  BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
		    		    Bitmap bitmap = drawable.getBitmap();
		    		    FileOutputStream outStream;
		    		    outStream = new FileOutputStream(pic);
		    	        success=bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); 
		    	        /* 100 to keep full quality of the image */
		    	        
		    	        outStream.flush();
		    	        outStream.close();
		    	        
		    	         
		    	 
		    	       
		    		  
		    	  }
		    	  catch (FileNotFoundException e) {
		    	        e.printStackTrace();
		    	    } catch (IOException e) {
		    	        e.printStackTrace();
		    	    }
		    	 
		    	  if (success) {
		    	        Toast.makeText(getApplicationContext(), "Image saved with success",
		    	                Toast.LENGTH_LONG).show();
		    	    } 
		    	    else {
		    	        Toast.makeText(getApplicationContext(),
		    	                "Error during image saving", Toast.LENGTH_LONG).show();
		    	    }
		    	  
		    	  File Json= new File(file,Title+".txt");
		    	  try{
		    		 
		    		  file.mkdirs();
		    		  FileWriter writer = new FileWriter(Json);
		    		  writer.append(",");
		    		  writer.append("{");
		    		  writer.append("\n\"id\": \"2847\",\n");
		    		  writer.append("\"lat\": ");
		    		  writer.append("\"");
		    		  writer.equals(Lat);
		    		  writer.append("\",\n");
		    		  writer.append("\"lng\": ");
		    		  writer.append("\"");
		    		  writer.equals(Long);
		    		  writer.append("\",\n");
		    		  writer.append("\'title\': ");
		    		  writer.append("\"");
		    		  writer.write(Title);
		    		  writer.append("\",\n");
		    		  writer.append("\"has_detail_page\": \"1\",\n");
		    		  writer.append("\"");
		    		 // writer.write(Description);
		    		  writer.append("\",");
		    		  writer.append("\"webpage\":\"\", \n");
		    		  writer.append("}");
		    		  writer.flush();
		    		  Toast.makeText( getApplicationContext(), "file saved", Toast.LENGTH_SHORT ).show();
		    		  writer.close();
		    	  }
		    	  catch (IOException e) {
		    	        // Unable to create file, likely because external storage is
		    	        // not currently mounted.
		    	        Log.w("ExternalStorage", "Error writing " + file, e);
		    	    }
		    	  
		    	    mExternalStorageAvailable = mExternalStorageWriteable = true;
		    	} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    		Toast.makeText( getApplicationContext(), "Unable to write to file.", Toast.LENGTH_SHORT ).show();
		    	    mExternalStorageAvailable = true;
		    	    mExternalStorageWriteable = false;
		    	} else {
		    		Toast.makeText( getApplicationContext(), "Unable to access SD card.", Toast.LENGTH_SHORT ).show();
		    	    mExternalStorageAvailable = mExternalStorageWriteable = false;
		    	}
		      
		     
		      
		}
	});
	
	   
	    
	Button Pic = (Button) findViewById(R.id.takePic);
	Pic.setOnClickListener(new View.OnClickListener(){
		public void onClick(View z){
			    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			    startActivityForResult(takePictureIntent, CAMERA_REQUEST);
			   		    
		}
	});
	
  }
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
        }  
    }
	
	
	 private void updateWithNewLocation(Location location) {
	       
	        String latLongString = "";
	        if (location != null) {
	            double lat = location.getLatitude();
	            double lng = location.getLongitude();
	            latLongString = "Lat:" + lat + "\nLong:" + lng;



	        } else {
	            latLongString = "No location found";
	        }
	        
	    }

	
	
	 private final LocationListener locationListener = new LocationListener() {
	        public void onLocationChanged(Location location) {
	            updateWithNewLocation(location);
	        }

	        public void onProviderDisabled(String provider) {
	            updateWithNewLocation(null);
	        }

	        public void onProviderEnabled(String provider) {
	        }

	        public void onStatusChanged(String provider, int status, Bundle extras) {
	        }
	    };



	

	@Override
	public void onLocationChanged(Location location) {
		
		Lat=location.getLatitude();
		Long=location.getLongitude();
	}
	@Override
	public void onProviderDisabled(String service) {
		Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
		
	}
	@Override
	public void onProviderEnabled(String service) {
		Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
		
	}
	@Override
	public void onStatusChanged(String service, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	} 

		
}
